package com.xzz.treeBST;

/**
 * @author: hhz
 * @create: 2021-12-21 09:32
 * 98. 验证二叉搜索树
 * 给你一个二叉树的根节点 root ，判断其是否是一个有效的二叉搜索树。
 * <p>
 * 有效 二叉搜索树定义如下：
 * <p>
 * 节点的左子树只包含 小于 当前节点的数。
 * 节点的右子树只包含 大于 当前节点的数。
 * 所有左子树和右子树自身必须也是二叉搜索树。
 **/
public class IsValidBST {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(5);
        TreeNode node2 = new TreeNode(4);
        TreeNode node3 = new TreeNode(6);
        TreeNode node4 = new TreeNode(3);
        TreeNode node5 = new TreeNode(7);

//        TreeNode node1 = new TreeNode(2);
//        TreeNode node2 = new TreeNode(1);
//        TreeNode node3 = new TreeNode(3);


        node1.left = node2;
        node1.right = node3;
        node3.left = node4;
        node3.right = node5;
        print(node1);
        System.out.println();
        System.out.println(isValidBST(node1));


    }

    public static boolean isValidBST(TreeNode root) {
        return isValid(root, null, null);
    }

    /* 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val */
    public static boolean isValid(TreeNode root, TreeNode max, TreeNode min) {
        if (root == null) {
            return true;
        }
        if (max != null && root.val >= max.val) {
            return false;
        }
        if (min != null && root.val <= min.val) {
            return false;
        }
        boolean valid = isValid(root.left, root, min);
        boolean valid1 = isValid(root.right, max, root);
        return valid && valid1;
    }

    public static void print(TreeNode root) {
        if (root != null) {
            System.out.print(root.val + ",");
            print(root.left);
            print(root.right);
        }
    }
}
